package org.theonept.travian.t4a.account;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.theonept.travian.model.Compte;
import org.theonept.travian.model.Message;
import org.theonept.travian.model.Rapport;
import org.theonept.travian.model.Ressource;
import org.theonept.travian.model.Village;
import org.theonept.travian.t4a.R;
import org.theonept.travian.t4a.message.MessageSectionFragment;
import org.theonept.travian.t4a.message.ReadMessageActivity;
import org.theonept.travian.t4a.report.ReportSectionFragment;
import org.theonept.travian.t4a.service.Travian4AndoidService;
import org.theonept.travian.t4a.village.VillageSectionFragment;
import org.theonept.travian.util.AsyncWeb;

import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.Toast;

public class CompteActivity extends FragmentActivity {
	private ArrayList<Message> messages;
	private ArrayList<Village> villages;
	private ArrayList<Rapport> rapports;
	/**
	 * The {@link android.support.v4.view.PagerAdapter} that will provide
	 * fragments for each of the sections. We use a
	 * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
	 * will keep every loaded fragment in memory. If this becomes too memory
	 * intensive, it may be best to switch to a
	 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
	 */
	SectionsPagerAdapter mSectionsPagerAdapter;
	private VillageSectionFragment fragmentVillage;
	private MessageSectionFragment fragmentMessage;
	private ReportSectionFragment fragmentReport;
	/**
	 * The {@link ViewPager} that will host the section contents.
	 */
	ViewPager mViewPager;
	private Compte compte;
	private Object compteAsync;
	public ArrayList<Ressource> ressources;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// This has to be called before setContentView
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.activity_compte);
		// Show the Up button in the action bar.

		// Create the adapter that will return a fragment for each of the three
		// primary sections of the app.
		mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

		// Set up the ViewPager with the sections adapter.
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setAdapter(mSectionsPagerAdapter);

		compte = (Compte) getIntent().getExtras().getSerializable("compte");
		String mode = getIntent().getExtras().getString("mode");
		if (mode != null) {
			if (mode.equals("message")) {
				mViewPager.setCurrentItem(2);
				Message message = (Message) getIntent().getExtras().getSerializable("message");
				if (message != null) {
					Intent intent = new Intent(this, ReadMessageActivity.class);
					intent.putExtra("compte", compte);
					intent.putExtra("message", message);
					startActivity(intent);
				}

			}
		}
		mViewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				// TODO Auto-generated method stub
				switch (arg0) {
				case 2:
					NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
					nm.cancel((int) (compte.getIdCompte() * Travian4AndoidService.ID_MESSAGE_NOTIFICATION));

					break;

				default:
					break;
				}
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub

			}
		});

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.compte, menu);
		menu.findItem(R.id.action_refresh);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_refresh:
			// This shows an indeterminate progress bar in the action bar
			if (compteAsync == null) {
				compteAsync = new CompteAsync(compte).execute(compte);
				return true;
			} else {
				return false;
			}

		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
	 * one of the sections/tabs/pages.
	 */
	public class SectionsPagerAdapter extends FragmentPagerAdapter {

		public SectionsPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {

			// getItem is called to instantiate the fragment for the given page.
			// Return a DummySectionFragment (defined as a static inner class
			// below) with the page number as its lone argument.
			switch (position) {
			case 0:
				if (fragmentVillage == null) {
					fragmentVillage = new VillageSectionFragment();

				}
				Bundle argsVillage = new Bundle();
				argsVillage.putSerializable("villages", villages);
				argsVillage.putSerializable("compte", compte);
				fragmentVillage.setArguments(argsVillage);

				return fragmentVillage;
			case 2:
				if (fragmentMessage == null) {
					fragmentMessage = new MessageSectionFragment();
				}
				Bundle argsMessage = new Bundle();
				argsMessage.putSerializable("compte", compte);
				argsMessage.putSerializable("messages", messages);
				fragmentMessage.setArguments(argsMessage);
				return fragmentMessage;
			default:
				if (fragmentReport == null) {
					fragmentReport = new ReportSectionFragment();

				}

				Bundle argsRepports = new Bundle();
				argsRepports.putSerializable("compte", compte);
				argsRepports.putSerializable("reports", rapports);
				fragmentReport.setArguments(argsRepports);
				return fragmentReport;
			}

		}

		@Override
		public int getCount() {
			// Show 3 total pages.
			return 3;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			Locale l = Locale.getDefault();
			switch (position) {
			case 0:
				return getString(R.string.title_village).toUpperCase(l);
			case 1:
				return getString(R.string.title_rapport).toUpperCase(l);
			case 2:
				return getString(R.string.title_message).toUpperCase(l);
			}
			return null;
		}
	}

	class CompteAsync extends AsyncWeb<Compte, Void, Boolean> {

		public CompteAsync(Compte compte) {
			super(compte);
			// TODO Auto-generated constructor stub
		}

		@Override
		protected void onCancelled() {
			compteAsync = null;
			setProgressBarIndeterminateVisibility(false);

			super.onCancelled();
		}

		@Override
		protected void onPreExecute() {
			setProgressBarIndeterminateVisibility(true);

			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if (result) {
				if (fragmentMessage != null) {
					fragmentMessage.setData(messages);
					fragmentMessage.getArguments().putSerializable("messages", messages);
				}
				if (fragmentVillage != null) {
					fragmentVillage.setData(villages);
					fragmentVillage.getArguments().putSerializable("villages", villages);
				}

				if (fragmentReport != null) {
					fragmentReport.setData(rapports);
					fragmentReport.getArguments().putSerializable("reports", rapports);
				}

			} else {
				Toast.makeText(getApplicationContext(), "Could not connect to account.", Toast.LENGTH_LONG).show();
				finish();
			}
			compteAsync = null;
			setProgressBarIndeterminateVisibility(false);
			super.onPostExecute(result);
		}

		@Override
		protected Boolean executeWebTask(Compte... params) {

			// TODO Auto-generated method stub
			if (compte.isEtat(true, true)) {

				List<Village> villages = compte.getVillages();
				for (Village village : villages) {
					village.getProduction();
				}
				CompteActivity.this.villages = (ArrayList<Village>) villages;
				CompteActivity.this.messages = (ArrayList<Message>) compte.getMessages();
				CompteActivity.this.rapports = (ArrayList<Rapport>) compte.getRapports();
				return true;
			}
			return false;
		}

	}

	@Override
	protected void onResume() {

		compteAsync = new CompteAsync(compte).execute(compte);

		super.onResume();
	}
}
